import {post} from '../../utils/http'
import {setLocalStorage} from '../../utils/localStorage'
import {LOGIN, CLEARLOGIN} from '../types'
import router from '../../router/index'
const state = {
  token: null,
  title: '',
  data: {
    user: '',
    valid: null,
    showApp: false,
    username: '',
    password: '',
    usernameRules: [
      (v) => !!v || '请输入用户名'
    ],
    passwordRules: [
      (v) => !!v || '请输入密码'
    ],
    alert: false,
    msg: null
  }
}

const mutations = {
  [LOGIN]: (state, playload) => {
    if (playload.validate()) {
      post('/api-token-auth/', {
        username: state.data.username,
        password: state.data.password
      }).then((response) => {
        setLocalStorage('admin-token', response['token'], 0.5)
        router.replace({ path: '/dashboard' })
      }).catch((error) => {
        console.log(error)
        state.data.alert = true
        state.data.msg = '用户名或密码错误！'
      })
    }
  },
  [CLEARLOGIN]: (state, playload) => {
    playload.reset()
    state.data.alert = false
  }
}

const actions = {
  [LOGIN]: ({commit}, playload) => {
    commit('login', playload)
  },
  [CLEARLOGIN]: ({commit}, playload) => {
    commit('clearLogin', playload)
  }
}

export default {
  state,
  mutations,
  actions
}
